<!-- 联系客户 -->
<template>
<div ref="contactBox" class="content-box box">
    <div class="box_Left">
        <div class="search">
            <el-input
                clearable
                @clear="getContactList"
                v-model="contactSearch"
            >
                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
        </div>
        <div @click="openContact(item,index)" class="contactList_item" :class="item.room_id==room_id?'active':''" v-for="(item,index) in contactList" :key="index">
            <div class="contactList_item_name">{{item.name}}</div>
            <div v-if="item.haveNewNum>0" class="contactList_item_tip">{{item.haveNewNum>999?'+999':item.haveNewNum}}</div>
        </div>
    </div>
    <div class="box_Right">
        <div class="title">
            <el-avatar  v-if="!!room_id" size="medium" :src="contactAvatar"></el-avatar>
            <div  v-if="!!room_id">{{contactName}}</div>
        </div>
        <!--有对话时，对话框-->
        <div v-if="!!room_id" class="chat_box" ref="chat_content" @scroll="scrollToBottom">
            <div
            v-for="(item, index) in chat_box_List"
            :key="index"
            class="chat_box_item"
            >
                <!--其他用户的消息展示-->
                <div v-if="item.from.uid !== meUid" class="content_other">
                    <el-avatar class="userImg" shape="square" size="medium" :src="$baseUrl+item.from.avatar"></el-avatar>
                    <div style="width:50%;display: flex;flex-direction: column;align-items: flex-start;">
                        <div class="userGroup">
                            <span class="username">{{ item.from.nickname.length>0?item.from.nickname:item.from.name }}</span>
                            <span class="usertime">{{ item.data.datetime }}</span>
                        </div>
                        <p v-if="item.data.type=='text'" class="userMsg" v-html="item.data.content"></p>
                        <p v-else class="userMsg">
                            <img @click="imgView($baseUrl+item.data.content.split(',')[0])" style="width:100px;cursor: pointer;" :src="$baseUrl+item.data.content.split(',')[0]" alt="">
                        </p>
                    </div>
                </div>
                <!-- 本用户的消息展示-->
                <div v-else class="content_me">
                    <el-avatar class="userImg" shape="square" size="medium" :src="$baseUrl+item.from.avatar"></el-avatar>
                    <div style="display: flex;flex-direction: column;align-items: flex-end;width:50%;">
                        <div style="flex-direction: row-reverse" class="userGroup">
                            <span class="username">{{ item.from.name }}</span>
                            <span class="usertime">{{ item.data.datetime }}</span>
                        </div>
                        <p v-if="item.data.type=='text'" class="userMsg" v-html="item.data.content"></p>
                        <p v-else class="userMsg">
                            <img @click="imgView($baseUrl+item.data.content.split(',')[0])" style="width:100px;cursor: pointer;" :src="$baseUrl+item.data.content.split(',')[0]" alt="">
                        </p>
                    </div>
                </div>
            </div>
            <!-- <div v-if="msg_loading" class="msgLoad">
                <i class="el-icon-loading"></i>
                正在加载
            </div> -->
        </div>
        <!--无对话时，对话框-->
        <div v-else class="chat_box chat_dialog_false">
            <span>{{$t('ContactCustomersLang.noText')}}</span>
        </div>
        <div v-if="!!room_id" class="input_box">
            <div class="toolbar">
                <el-upload
                class="avatar-uploader"
                action="#"
                :on-change="handleChange"
                :show-file-list="false"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PBG"
                :auto-upload="false">
                    <i class="el-icon-picture-outline"></i>
                </el-upload>
            </div>
            <el-input
                ref="textInput"
                resize="none"
                type="textarea"
                v-model="input_value">
            </el-input>
            <i style="cursor: pointer;" class="el-icon-s-promotion sendBtn" @click="sendInput"></i>
        </div>
    </div>

</div>
</template>

<script>
export default {
  components: {
  },
  data(){
    return{
        contactSearch:'',
        contactName:'',
        contactAvatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        contactList:[],
        meUid:JSON.parse(sessionStorage.getItem('userData')).uid,
        meName:JSON.parse(sessionStorage.getItem('userData')).name,
        room_id:'',
        chat_box_List:[],
        msg_loading:false,
        input_value:'',
        pageinfo:{
            limit:10,
            page_all:1,
            page:1
        },
    }
  },
  computed: {
  },
  created() {
    if("WebSocket" in window){
        this.ws = new WebSocket(process.env.VUE_APP_WSS);
    }else{
        this.$notify.error({
          title: this.$t('ContactCustomersLang.error_title'),
          message: this.$t('ContactCustomersLang.error_text'),
        });
    }
  },
  mounted(){
    this.ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    this.ws.addEventListener("close", this.handleWsClose.bind(this), false);
    this.ws.addEventListener("error", this.handleWsError.bind(this), false);
    this.ws.addEventListener("message", this.handleWsMessage.bind(this), false);
    this.getContactList()
  },
  beforeDestroy(){
    this.ws.close()
  },
  methods:{
    keydownFuc(event){
        if(event.ctrlKey && (event.key === 'Enter' || event.keyCode === 13)){
            this.input_value+='\n'
        }else if(event.keyCode===13){
              event.preventDefault();
              this.sendInput()
        }
    },
    handleWsOpen() {
        console.log("客户WebSocket连接成功");
        let obj={type:"init",id:this.meUid};
        this.ws.send(JSON.stringify(obj));
    },
    handleWsClose(e) {
      console.log("客户WebSocket2关闭", e);
    },
    handleWsError(e) {
      console.log("WebSocket2发生错误", e);
    },
    handleWsMessage(e) {
        console.log("客户消息",JSON.parse(e.data));
        const data = JSON.parse(e.data);
        let created_by=JSON.parse(sessionStorage.getItem('userData')).created_by.length==0?JSON.parse(sessionStorage.getItem('userData')).uid:JSON.parse(sessionStorage.getItem('userData')).created_by
        if(data.type=="chatMessage"){
            if(data.room_creator_id===created_by){
                return
            }
            //判断消息是否为当前客户发送的消息
            if(data.room_id==this.room_id){
                //所有接收到的数据在这里处理，然后赋值渲染到页面上
                this.chat_box_List.push(data);
                // //对话框默认滚动到底部
                let dom = this.$refs.chat_content
                this.$nextTick(() => {
                    if(!!dom){
                        dom.scrollTop = dom.scrollHeight;
                    }
                });
            }else{
                
                let index=this.contactList.findIndex(item=>{return item.room_id==data.room_id})
                console.log(index)
                if(index==-1){
                    this.$get("sonGroupChats", { keyword: this.contactSearch,room_id:data.room_id }).then(
                        (res) => {
                            if(res.data.length>0){
                                let obj=JSON.parse(JSON.stringify(res.data[0]))
                                this.contactList.unshift(obj)
                            }
                        }
                    );
                }else{
                    let obj=this.contactList.splice(index,1)[0]
                    obj.haveNewNum+=1
                    this.contactList.unshift(obj)
                }
            }
        }
    },
    getContactList(){
        this.$get("sonGroupChats", { keyword: this.contactSearch }).then(
            (res) => {
                this.contactList = res.data;
            }
        );
    },
    search(){
        this.getContactList()
    },
    openContact(data,index){
        var testData = {type:"room",room_id:data.room_id};
        this.ws.send( JSON.stringify(testData) );
        this.contactList[index].haveNewNum=0
        this.contactName=data.name
        this.contactAvatar=this.$baseUrl+data.avatar
        this.chat_box_List=[]
        this.pageinfo={
            limit:10,
            page_all:1,
            page:1
        }
        this.$nextTick(()=>{
            this.room_id=data.room_id
            this.$nextTick(()=>{
                this.getChatList()
                this.$refs.textInput.$el.addEventListener('keydown', this.keydownFuc);
            })
        })
    },
    getChatList(){
        const dom =this.$refs.chat_content
        let domHeight=0
        if(!!dom){
            domHeight=dom.scrollHeight //记录原有内容高度
        }
        this.$get("historyMsg", {limit:this.pageinfo.limit,page:this.pageinfo.page,room_id: this.room_id }).then(
            (res) => {
                this.msg_loading=false
                this.chat_box_List.unshift(...res.data)
                this.pageinfo = res.pageinfo
                this.$nextTick(()=>{
                    if(!!dom){
                        dom.scrollTop=dom.scrollHeight-domHeight //让滚动条不动
                    }
                })
            }
        );
    },
    scrollToBottom(e) {
        //触底判断
        if (e.target.scrollTop == 0) {
            if (this.pageinfo.page_all == this.pageinfo.page) {
              return;
            }
            this.pageinfo.page++;
            this.msg_loading=true
            this.getChatList();
        }
    },
    handleChange(file,fileList) {
        let img_url=URL.createObjectURL(file.raw)
        let params = new FormData();
            params.append("htfile",file.raw);
        this.$postForm("uploadFile", params).then((res) => {
            let obj={
                type: "chatMessage",
                room_id: this.room_id,
                msg_id: new Date().getTime(),
                data: {
                    type: "htfile",
                    content: res.data.file_url+','+img_url
                },
                from: {
                    uid: this.meUid,
                    name: this.meName,
                    avatar: ""
                }
            }
            this.ws.send(JSON.stringify(obj));
        });
    },
    imgView(url){
        console.log(url)
        eventBus.$emit("imgViewer",[url]);
    },
    sendInput(){
        if (this.input_value === "") {
            return;
        }	
        let obj={
            type: "chatMessage",
            room_id: this.room_id,
            msg_id: new Date().getTime(),
            data: {
                type: "text",
                content: this.input_value.replace(/\n/g,'<br>')
            },
            from: {
                uid: this.meUid,
                name: this.meName,
                avatar: ""
            }
        }
        this.ws.send(JSON.stringify(obj));
        this.input_value = "";
    },

  }
}
</script>
<style scoped lang="less">
    .box{
        padding: 0 !important;
        margin: 15px;
        margin-left: 0;
        display: flex;
        flex-direction: row;
        border: 1px solid #ccc;
        border-radius: 5px;
        .box_Left{
            width: 200px;
            height: 100%;
            overflow-y: auto;
            overflow-x: hidden; 
            background-color: #fff;
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
            .search{
                border-bottom: 1px solid #ccc;
                padding: 10px;
                /deep/ .el-input-group--append .el-input__inner{
                    border-top-left-radius: 4px !important;
                    border-bottom-left-radius: 4px !important;
                }
                /deep/ .el-input-group__append{
                    padding: 0;
                    .el-button{
                        margin: 0;
                        padding: 5px 15px;
                    }
                }
            }
            .contactList_item{
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 20px;
                line-height: 20px;
                padding: 10px;
                font-size: 18px;
                cursor: pointer;
                .contactList_item_name{
                    width: 90%;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
                .contactList_item_tip{
                    padding: 0 5px;
                    border-radius: 8px;
                    height: 16px;
                    line-height: 16px;
                    background-color: #ff1a1a;
                    color: #fff;
                    font-size: 10px;
                    text-align: center;
                }
            }
            .contactList_item:hover {
                color: white !important;
                background: #3989fa !important;
                border-radius: 4px;
            }
            .contactList_item.active {
                color: white !important;
                background: #3989fa !important;
                border-radius: 4px;
            }
        }
        .box_Right{
            display: flex;
            flex-direction: column;
            border-left: 1px solid #ccc;
            width: calc(100% - 202px);
            border-top-right-radius: 4px;
            .title{
                display: flex;
                align-items: center;
                gap: 10px;
                height: 46px;
                padding: 0 10px;
                border-bottom: 1px solid #ccc;
                background-color: #fff;
                font-size: 20px;
            }
            .chat_box{
                position: relative;
                flex: 1;
                padding: 10px;
                overflow-y: scroll;
                background-color: #f5f5f5;
                .chat_box_item{
                    margin-left: 5px;
                    margin-bottom: 20px;
                    .content_other{
                        display: flex;
                        align-items: flex-start;
                        gap: 10px;

                        .userMsg:before {
                            left: -10px;
                            border-color:transparent #fff transparent transparent; /* 筋头颜色 */
                        }
                    }
                    .content_me{
                        display: flex;
                        align-items: flex-start;
                        gap: 10px;
                        flex-direction: row-reverse;
                        .userMsg{
                            background-color: #89d961;
                        }
                        .userMsg:before {
                            right: -10px;
                            border-color:transparent transparent transparent #89d961; /* 筋头颜色 */
                        }
                    }
                    .userImg{
                        margin-top: 5px;
                    }
                    .userGroup{
                        display: flex;
                        gap: 10px;
                        align-items: flex-end;
                        margin-bottom: 5px;
                        .username{
                            font-size: 16px;
                        }
                        .usertime{
                            font-size: 12px;
                            color: #aaa;
                        }
                    }
                    .userMsg{
                        position: relative;
                        max-width: 95%;
                        background-color: #fff;
                        color: #000;
                        border-radius: 6px;
                        padding: 8px;
                        margin-left: 5px;
                        word-wrap: break-word;
                        white-space: pre-line;
                    }
                    .userMsg:before {
                        content:'';
                        position: absolute;
                        top: 5px;
                        border-width:5px;/*箭头大小*/
                        border-style:solid;/*箭头样式*/
                        border-color:transparent #fff transparent transparent; /* 筋头颜色 */
                    }
                }
                .msgLoad{
                    position: absolute;
                    color: #aaa;
                    top: 0;
                    left: 50%;
                    transform: translateX(-50%);
                }
            }
            .chat_box::-webkit-scrollbar{
                width: 0;
                height: 0;
            }
            .chat_dialog_false{
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .input_box{
                position: relative;
                background-color: #fff;
                .toolbar{
                    padding: 5px 15px;
                    border-top: 1px solid #DCDFE6;
                    font-size: 20px;
                }
                /deep/ .el-textarea {
                    padding-bottom: 50px;
                    .el-textarea__inner{
                        min-height: 100px !important;
                        border-radius: 0;
                        border-bottom-right-radius: 4px;
                        border: 0;
                    }
                    .el-textarea__inner:focus{
                        border-color: #DCDFE6;
                    }
                    .el-textarea__inner::-webkit-scrollbar{
                        width: 0;
                        height: 0;
                    }
                }
                .sendBtn{
                    position: absolute;
                    right: 10px;
                    bottom: 10px;
                    font-size: 35px;
                    color: #6c9ee5;
                }
            }
        }
    }
</style>